﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using SpLocalizer.Common;
using SpLocalizer.Common.DbApi;


namespace SpLocalizer.ContentSourceProviders.SpWeb
{
    public class SpListContent : AbstractSpContent, IDisposable
    {

        private SPWeb web = null;
        private SPList list = null;

        public override object ContentSource
        {
            get
            {
                if (this.list != null)
                    return this.list;
                else
                    return this.web;
            }
            set
            {
                if (value is SPList)
                {
                    this.list = (SPList)value;
                }
                else if (value is SPWeb)
                {
                    this.web = (SPWeb)value;
                }
                else
                {
                    throw new ArgumentException(String.Format("Illegal argument type {0}", value.GetType().FullName));
                }
                
            }
        }


        internal IEnumerable<AbstractContent> Bind(SPList list, bool IncludeDescandants)
        {
            this.list = list;
            this.ContentTitle = list.Title;
            this.ContentId = list.ID.ToString();
            this.ContentAddress = list.DefaultViewUrl;

            List<AbstractContent> BindResults = new List<AbstractContent>();
            BindResults.Add(this);

            //if (IncludeDescandants)
            return BindResults;
        }

        public override IEnumerable<AbstractContent> Bind(string ResourceUrl, bool IncludeDescandants)
        {
            if (this.web != null)
            {
                try
                {
                    return this.Bind(this.web.GetList(ResourceUrl), IncludeDescandants);
                }
                finally
                {
                    this.web = null; // we don't need parent web
                }
            }else{
                return null;
            }
        }

        public override IEnumerable<AbstractContent> Bind(Guid ResourceId, bool IncludeDescandants)
        {
            if (this.web != null)
            {
                try
                {
                    return this.Bind(this.web.Lists[ResourceId], IncludeDescandants);
                }
                finally
                {
                    this.web = null;// we don't need parent web
                }
            }
            else
            {
                return null;
            }
        }

        public override IEnumerable<Common.BaseTranslationTask> BuildTranslationTasks(System.Globalization.CultureInfo FromLanguage, 
            System.Globalization.CultureInfo ToLanguage)
        {
            List<BaseTranslationTask> TranslationTasks = new List<BaseTranslationTask>();

            // Add task for title translation
            if (this.list.TitleResource != null && !String.IsNullOrEmpty(this.list.Title))
            {
                TranslationTasks.Add(new SpUserResourceLocalizationTask(FromLanguage, ToLanguage, this.list.TitleResource));
            }
            // Add task for description translation
            if (this.list.DescriptionResource != null && !String.IsNullOrEmpty(this.list.Description))
            {
                TranslationTasks.Add(new SpUserResourceLocalizationTask(FromLanguage, ToLanguage, this.list.DescriptionResource));
            }

            // Add task for field translation
            foreach (SPField field in this.list.Fields)
            {                 
                // If SUserResource is null = this is a system property. No translation required.
                if (field.Title != null && !String.IsNullOrEmpty(field.Title) && field.TitleResource != null)
                {
                 
                    TranslationTasks.Add(new SpUserResourceLocalizationTask(FromLanguage, ToLanguage, field.TitleResource));
                }

                if (field.Description != null && !String.IsNullOrEmpty(field.Description) && field.DescriptionResource != null)
                {
                    TranslationTasks.Add(new SpUserResourceLocalizationTask(FromLanguage, ToLanguage, field.DescriptionResource));
                }
            }


            // Add task for contenttypes translation
            if (this.list.ContentTypesEnabled)
                foreach (SPContentType contenttype in this.list.ContentTypes)
                {
                    if (contenttype.Name != null && !String.IsNullOrEmpty(contenttype.Name))
                    {
                        TranslationTasks.Add(new SpUserResourceLocalizationTask(FromLanguage, ToLanguage, contenttype.NameResource));
                    }

                    if (contenttype.Description != null && !String.IsNullOrEmpty(contenttype.Description))
                    {
                        TranslationTasks.Add(new SpUserResourceLocalizationTask(FromLanguage, ToLanguage, contenttype.DescriptionResource));
                    }
                }



            return TranslationTasks;
        }

        /// <summary>
        /// Export translations back into content source
        /// </summary>
        /// <param name="TranslationTask"></param>
        public override void ExportContentTranslations(Common.BaseTranslationTask TranslationTask)
        {
            if (TranslationTask is SpUserResourceLocalizationTask)
            {

                string ResourceKey = ((SpUserResourceLocalizationTask)TranslationTask).ResourceKey;
                SPUserResource resource = this.list.UserResources[ResourceKey];
                if (resource == null)
                {
                    if (SpUserResourceLocalizationTask.ListTitle_ResourceName.Equals(ResourceKey))
                    {
                        resource = this.list.TitleResource;
                    }
                    else if (SpUserResourceLocalizationTask.ListDescription_ResourceName.Equals(ResourceKey))
                    {
                        resource = this.list.DescriptionResource;
                    }
                    else if (ResourceKey.StartsWith(SpUserResourceLocalizationTask.FieldTitle_ResourceName))
                    {
                        string fieldInternalName = ResourceKey.Substring(SpUserResourceLocalizationTask.FieldTitle_ResourceName.Length);
                        // Get field internal name from resource name

                        SPField field = this.list.Fields.GetFieldByInternalName(fieldInternalName);
                        resource = field.TitleResource;
                    }
                    else if (ResourceKey.StartsWith(SpUserResourceLocalizationTask.FieldDescription_ResourceName))
                    {
                        string fieldInternalName = ResourceKey.Substring(SpUserResourceLocalizationTask.FieldDescription_ResourceName.Length);
                        // Get field internal name from resource name

                        SPField field = this.list.Fields.GetFieldByInternalName(fieldInternalName);
                        resource = field.DescriptionResource;
                    }
                    else if (ResourceKey.StartsWith(SpUserResourceLocalizationTask.ContentTypeName_ResourceName))
                    {
                        string contentTypeId = ResourceKey.Substring(SpUserResourceLocalizationTask.ContentTypeName_ResourceName.Length);
                        // Get content type id from resource name
                        SPContentTypeId cntId = new SPContentTypeId(contentTypeId);

                        SPContentType contentType = this.list.ContentTypes[cntId];
                        resource = contentType.NameResource;
                    }
                    else if (ResourceKey.StartsWith(SpUserResourceLocalizationTask.ContentTypeDescription_ResourceName))
                    {
                        string contentTypeId = ResourceKey.Substring(SpUserResourceLocalizationTask.ContentTypeDescription_ResourceName.Length);
                        // Get content type id from resource name
                        SPContentTypeId cntId = new SPContentTypeId(contentTypeId);

                        SPContentType contentType = this.list.ContentTypes[cntId];
                        resource = contentType.DescriptionResource;
                    }
                    else
                    { // Unknown resource type. Try to construct
                        SPResourceType resType = (SPResourceType)Enum.Parse(typeof(SPResourceType),
                                                ((SpUserResourceLocalizationTask)TranslationTask).ResourceType);

                        resource = new SPUserResource(ResourceKey, resType);
                        resource.SetValueForUICulture(TranslationTask.FromLanguage, TranslationTask.SourceText);
                        resource.SetValueForUICulture(TranslationTask.ToLanguage, TranslationTask.TranslatedText);
                        this.list.UserResources.Add(resource);
                    }
                }

                resource.SetValueForUICulture(TranslationTask.ToLanguage, TranslationTask.TranslatedText);
                resource.Update();

            }
            else
            {
                throw new ArgumentException(String.Format("Illegal type {0} for translation task id {1}",
                    TranslationTask.GetType().ToString(), TranslationTask.TaskId));
            }
        }
        
        /// <summary>
        /// 
        /// </summary>
        public override void PerformExportDone()
        {
            //Nothing to perform here yet
        }

        public void Dispose()
        {
            if (this.web != null)
            {
                //Web will be closed in parent 
                this.web = null;
            }
        }
    }
}
